/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.snk.kof.component.validator;


import cn.hutool.core.util.StrUtil;
import com.snk.kof.common.exception.BusinessException;
import com.snk.kof.common.utils.Executor;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author keshan
 * @date 2022-01-02 下午7:23
 */
public class ValidatorUtil {

    private static final String SEPARATOR = "; ";

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    public static void validateEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = VALIDATOR.validate(object, groups);
        Executor.get().execIf(constraintViolations, CollectionUtils::isNotEmpty, s -> {
            String errorMessage = constraintViolations.stream()
                    .map(constraint -> StrUtil.concat(Boolean.TRUE, constraint.getPropertyPath().toString(), StrUtil.COLON, constraint.getMessage()))
                    .collect(Collectors.joining(SEPARATOR));
            throw new BusinessException(errorMessage);
        });
    }

}
